package com.talent.common.exception;

import com.talent.common.enums.TalentResponse;
import com.talent.common.model.TalentResult;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @ClassName：GlobalException
 * @Author: hszhou
 * @Date: 2025/2/15 14:35
 * @Description: 必须描述类做什么事情, 实现什么功能
 */
@RestControllerAdvice
public class GlobalException {


    @ExceptionHandler(value = TalentException.class)
    public TalentResult handleTalentException(TalentException exception){

        TalentResponse response = exception.getResponse();
        return TalentResult.error(response);
    }

    /**
     * 方法参数校验失败的异常
     * @param exception
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public TalentResult handleMethodArgumentNotValidException(MethodArgumentNotValidException exception){
        BindingResult bindingResult = exception.getBindingResult();
        if(bindingResult.hasErrors()){
            FieldError fieldError = bindingResult.getFieldError();
            if(fieldError!=null){
                return TalentResult.error(fieldError.getDefaultMessage());
            }
        }
        return TalentResult.error(exception.getMessage());
    }

    /**
     * 对象内部使用Validate 没有校验成功的异常
     * @param exception
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    public TalentResult handleBindException(BindException exception){
        BindingResult bindingResult = exception.getBindingResult();
        if(bindingResult.hasErrors()){
            FieldError fieldError = bindingResult.getFieldError();
            if(fieldError!=null){
                return TalentResult.error(fieldError.getDefaultMessage());
            }
        }
        return TalentResult.error(exception.getMessage());
    }
}
